/**
 * Created by ${PRODUCT_NAME}.
 * User: skylerparr
 * Date: 12/18/10
 * Time: 1:08 PM
 * To change this template use File | Settings | File Templates.
 */
package com.thoughtorigin.relay {
import com.thoughtorigin.deeplink.DeepLinker;
import com.thoughtorigin.flux.Flux;
import com.thoughtorigin.service.Command;
import com.thoughtorigin.service.Message;
import com.thoughtorigin.service.Service;
import com.thoughtorigin.service.ServiceLocator;

import com.thoughtorigin.util.isBlank;

import flash.events.Event;
import flash.events.EventDispatcher;

public class ServiceMessageRelay extends EventDispatcher implements MessageRelay {

    private var _serviceLocator: ServiceLocator;
    private var _deeplinker: DeepLinker;

    public function relayMessage(msg:Message):void {
        if(msg.updateDeeplink) {
            _deeplinker.setDeepLink(msg);
            return;
        }

        _serviceLocator.locateService(msg.serviceName, function(service: Service): void {
            if(!service.hasEventListener(ResponseEvent.RESPONSE)) {
                service.addEventListener(ResponseEvent.RESPONSE, function(payload:ResponseEvent): void {
                    if(service.createNew) {
                        service.removeEventListener(ResponseEvent.RESPONSE, arguments.callee);
                    }
                    if(msg.directCallback != null) {
                        msg.directCallback.call(this, payload.event);
                    } else {
                        dispatchEvent(payload.event);
                    }
                });
            }
            if(!isBlank(msg.action)) {
                try {
                    service[msg.action](msg);
                } catch(e: ReferenceError) {
                    throw new ServiceRelayException("unable to call action : " + msg.action);
                }
            } else {
                service.handoff(msg);
            }
        });
    }

    [Inject]
    public function set serviceLocator(value: ServiceLocator): void {
        _serviceLocator = value;
    }

    [Inject]
    public function set deeplinker(value: DeepLinker): void {
        _deeplinker = value;
        _deeplinker.addEventListener(Command.COMMAND_EVENT, relayMessage);
    }


    override public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {
        super.addEventListener(type, listener, useCapture, priority, useWeakReference);
    }
}
}
